import { getAssignParamFromUrl } from 'src/utils/utils'

let callbackS = null
let callbackE = null

const fixedParams = {
  client_id: 'dingxr1bykvrk7fjikff', prompt: 'consent', scope: 'openid', response_type: 'code'
}

const handleMessage = e => {
  const { data, origin } = e
  if (/login\.dingtalk\.com/.test(origin) && data) {
    if (data.success && data.redirectUrl) {
      const { redirectUrl } = data
      const state = getAssignParamFromUrl(redirectUrl, 'state')
      const authCode = getAssignParamFromUrl(redirectUrl, 'authCode')
      callbackS && callbackS({ redirectUrl, authCode, state, other: fixedParams })
    } else {
      const errorMsg = getAssignParamFromUrl(data.redirectUrl, 'error')
      callbackE && callbackE(errorMsg)
    }
  } else callbackE && callbackE(data.errorMsg)

  callbackE = null
  callbackS = null
}

const formatUrl = loginParams => {
  let url = 'https://login.dingtalk.com/oauth2/auth?iframe=true'
  for (const key in loginParams) {
    if (loginParams[key]) url += `&${key}=${loginParams[key]}`
  }

  return url
}

const emptyList = ['undefined', undefined, null, 'null']

export const DDLogin = (frameParams = {}, loginParams = {}, successCbk, errorCbk) => {
  callbackE = errorCbk
  callbackS = successCbk

  if (!frameParams.id) return errorCbk && errorCbk('Element not found')
  // if (!loginParams.scope) return errorCbk && errorCbk('Missing parameters scope')
  // if (!loginParams.client_id) return errorCbk && errorCbk('Missing parameters client_id')
  if (!loginParams.redirect_uri) return errorCbk && errorCbk('Missing parameters redirect_uri')
  // if (!loginParams.response_type) return errorCbk && errorCbk('Missing parameters response_type')
  const node = document.getElementById(frameParams.id) || null

  if (!node) return errorCbk && errorCbk('Element not found')
  node.innerHTML = ''

  const frame = document.createElement('iframe')

  if (!frame || emptyList.includes(typeof window.addEventListener)) {
    return errorCbk && errorCbk('Browser not support')
  }

  window.removeEventListener('message', handleMessage, false)

  node.appendChild(frame)

  frame.style = 'border: 0; overflow: hidden;'

  frame.src = formatUrl({ ...loginParams, ...fixedParams })
  frame.width = frameParams.width || 300
  frame.height = frameParams.height || 300

  window.addEventListener('message', handleMessage, false)
}